package com.yibing.test.tdd.controller;

import java.util.HashMap;
import java.util.Map;

public class DefaultController implements Controller {

	private Map<String, RequestHandler> handlers = new HashMap<String, RequestHandler>();
	
	@Override
	public void addHandler(Request request, RequestHandler handler) {
		if (handlers.containsKey(request.getName())) {
			throw new RuntimeException("Request " + request.getName() + " already has a handler");
		}
		
		handlers.put(request.getName(), handler);
	}

	@Override
	public Response processRequest(Request request) {
		Response response;
		try {
			response = getHandler(request).process(request);
		} catch (Exception e) {
			response = new ErrorResponse(request, e);
		}
		return response;
	}
	
	public RequestHandler getHandler(Request request) {
		RequestHandler result = handlers.get(request.getName());
		if (result == null) {
			throw new RuntimeException("Cannot find handler for " + request.getName());
		} else {
			return result;
		}
	}

}
